<!-- 我的排版 -->
<script lang="ts" setup>
import { onMounted, ref, defineProps, defineEmits,watch,computed } from 'vue';
import { Delete, Plus, Search, Refresh, EditPen } from '@element-plus/icons-vue'
import { ElTable } from 'element-plus'
// 分页
import type { ComponentSize, TableInstance } from 'element-plus'
import type { TableColumnCtx } from 'element-plus'//表格
import http from '@/http';
import { da } from 'element-plus/es/locale';
import dayjs from 'dayjs'
interface User {
    id: string
    name: string
    amount1: string
    amount2: string
    amount3: number
}

interface SpanMethodProps {
    row: User
    column: TableColumnCtx<User>
    rowIndex: number
    columnIndex: number
}

const arraySpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex,
}: SpanMethodProps) => {
    if (rowIndex % 2 === 0) {
        if (columnIndex === 0) {
            return [1, 2]
        } else if (columnIndex === 1) {
            return [0, 0]
        }
    }
}

const objectSpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex,
}: SpanMethodProps) => {
    if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
            return {
                rowspan: 2,
                colspan: 1,
            }
        } else {
            return {
                rowspan: 0,
                colspan: 0,
            }
        }
    }
}


let time = ref('')
// 定义响应式变量
const currentDate = ref('');
const mondayDate = ref('');
const sundayDate = ref('');
//挂载完成之后
onMounted(() => {
    // 获取当前日期
    const now = new Date();
    // 格式化当前日期
    currentDate.value = formatDate(now);

    // 获取当前日期是星期几（0 - 6，0 表示周日）
    const dayOfWeek = now.getDay();
    // 计算周一的偏移量，如果是周日则偏移 6 天，否则偏移当前星期几减 1 天
    const offset = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
    // 创建周一的日期对象
    const monday = new Date(now);
    // 将日期设置为周一
    monday.setDate(now.getDate() - offset);
    // 格式化周一的日期
    mondayDate.value = formatDate(monday);

    // 创建周日的日期对象
    const sunday = new Date(monday);
    // 将日期设置为周日（在周一的基础上加上 6 天）
    sunday.setDate(monday.getDate() + 6);
    // 格式化周日的日期
    sundayDate.value = formatDate(sunday);
    getScheduling();
})

// 格式化日期的函数
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
//封装查询排版信息
// 格式化显示日期
function formatDay(dateStr) {
    const date = dayjs(dateStr)
    const month = date.month() + 1
    const day = date.date()
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const dayOfWeek = weekdays[date.day()]
    return `${month}-${day}(${dayOfWeek})`
}

// 上午时段
function hasMorningSchedule(row, date) {
  return (row.fhisSchedulingUserDepts || []).some(
    item => item.schedulingDay === date && item.subsectionType === '1' // 时段类型判断
  );
}

function getMorningSchedule(row, date) {
  const schedule = (row.fhisSchedulingUserDepts || []).find(
    item => item.schedulingDay === date && item.subsectionType === '1'
  );
  
  // 根据 schedulingType 返回
  return schedule?.schedulingType === '1' 
    ? '门诊' 
    : schedule?.schedulingType === '2' 
      ? '急诊' 
      : '';
}

// 中午时段
function hasAfternoonSchedule(row, date) {
  return (row.fhisSchedulingUserDeptszhho || []).some(
    item => item.schedulingDay === date && item.subsectionType === '2'
  );
}

function getAfternoonSchedule(row, date) {
  const schedule = (row.fhisSchedulingUserDeptszhho || []).find(
    item => item.schedulingDay === date && item.subsectionType === '2'
  );
  
  return schedule?.schedulingType === '1' 
    ? '门诊' 
    : schedule?.schedulingType === '2' 
      ? '急诊' 
      : '';
}

// 晚上时段（关键修正）
function hasEveningSchedule(row, date) {
  return (row.fhisSchedulingUserDeptswan || []).some(
    item => item.schedulingDay === date && item.subsectionType === '3' // 时段类型匹配
  );
}

function getEveningSchedule(row, date) {
  const schedule = (row.fhisSchedulingUserDeptswan || []).find(
    item => item.schedulingDay === date && item.subsectionType === '3'
  );
  
  return schedule?.schedulingType === '1' 
    ? '门诊' 
    : schedule?.schedulingType === '2' 
      ? '急诊' 
      : '';
}


//修改
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  }
});

const tableData = ref([
{
    title: '上午',
    timeSlot: 1, // 添加时段标识
    schedules: {} // 初始化空对象
  },
  {
    title: '下午',  
    timeSlot: 2,
    schedules: {}
  },
  {
    title: '晚上', 
    timeSlot: 3,
    schedules: {}
  }
]);

const submitForm = () => {
  // 这里可以添加表单提交的逻辑，比如将数据发送到后端
  console.log('提交表单', tableData.value);
};
const isModalVisible = ref(false);
watch (isModalVisible,()=>{
    if(!isModalVisible.value){
        getScheduling();
    }
})
//获取门诊消息
// 获取时段类型字典
let timePeriod = ref([])
const fetchDictData = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
     // 在原始数据基础上添加新项
     timePeriod.value = [...res, { 
      dict_value: '', 
      dict_label: '无', 
    }];
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};
// 添加状态变量
const currentEditingDoctor = ref<{
  userId: string;
  userName: string;
  deptId: String;
}>({ userId: '', userName: '',deptId:'' });
//
// 在 <script setup> 中添加以下方法
const handleScheduleChange = async (row: any, date: string,schedulingType :String) => {
    let scheDuling=ref({
        userId:currentEditingDoctor.value.userId,
        deptId:currentEditingDoctor.value.deptId,
        schedulingDay:date,
        subsectionType:row.timeSlot,
        schedulingType:schedulingType
    })
    
    //发送http请求
    http.post("/scheduling/addScheduling",scheDuling.value).then((res)=>{
        console.log("成功")
    }).catch((res)=>{
        console.log("失败")
    })

};
//// 修改打开模态框的方法
const openEditModal = (row: any) => {
  isModalVisible.value = true;

  currentEditingDoctor.value = {
    userId: row.userId,
    userName: row.userName,
    deptId: row.deptId
  };
   // 验证传入数据
   if (!row?.userId || !row?.userName) {
    console.error('无效的行数据:', row);
    return;
  }

  currentEditingDoctor.value = { ...row }; // 使用展开运算符确保响应性
  
  // 调试输出
  console.log('设置后的响应式对象:', currentEditingDoctor.value);
  console.log('序列化结果:', JSON.parse(JSON.stringify(currentEditingDoctor.value)))
   // 根据当前行的排班数据设置tableData的schedules默认值
   weekDays.value.forEach(day => {
    const morningSchedule = getMorningSchedule(row, day.date);
    const afternoonSchedule = getAfternoonSchedule(row, day.date);
    const eveningSchedule = getEveningSchedule(row, day.date);
    tableData.value[0].schedules[day.date] = morningSchedule? getDictValueByLabel(timePeriod.value, morningSchedule) : '';
    tableData.value[1].schedules[day.date] = afternoonSchedule? getDictValueByLabel(timePeriod.value, afternoonSchedule) : '';
    tableData.value[2].schedules[day.date] = eveningSchedule? getDictValueByLabel(timePeriod.value, eveningSchedule) : '';
  });
  console.log(row)
 
  console.log(tableData.value)
  console.log("用户值"+currentEditingDoctor.value)
}
// 辅助函数：根据标签获取字典值
function getDictValueByLabel(dictArray, label) {
  return dictArray.find(item => item.dict_label === label)?.dict_value || '';
}
let Pages=ref([])
//获取排班数据
function getScheduling() {
    let startDate2=ref(dateRange.value[0]);
    let dateRange2=ref(dateRange.value[1]);
    console.log(dateRange.value)
    console.log(dateRange.value)
    http.get('/scheduling/getScheduling2', {
        params: {
            startDate:startDate2.value ,
            endDate: dateRange2.value
        }
    }).then((res)=>{ 
        Pages.value=res
        
    })
}
// 修改获取默认日期范围的方法
const getDefaultDateRange = () => {
    const today = dayjs();
    // 计算到周一的偏移量（dayjs的day()周日=0，周一=1）
    const day = today.day();
    const subtractDays = day === 0 ? 6 : day - 1;
    const startDate = today.subtract(subtractDays, 'day');
    const endDate = startDate.add(6, 'day');
    return [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')];
};
const defaultDateRange = ref(getDefaultDateRange())
const dateRange = ref(getDefaultDateRange())
// 计算当前选择日期范围内的日期
const weekDays = computed(() => {
    if (!dateRange.value || dateRange.value.length !== 2) return []

    const days = []
    const startDate = dayjs(dateRange.value[0])
    const endDate = dayjs(dateRange.value[1])

    let currentDate = startDate
    while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
        days.push({
            date: currentDate.format('YYYY-MM-DD'),
            dayOfWeek: currentDate.day()
        })
        currentDate = currentDate.add(1, 'day')
    }

    return days
})

//
// 监听日期范围变化
watch(dateRange, (newVal) => {
    if (newVal && newVal.length === 2) {
        getScheduling();
    }
}, { immediate: true });

// 周导航方法
const prevWeek = () => {
    const start = dayjs(dateRange.value[0]).subtract(7, 'day');
    dateRange.value = [start.format('YYYY-MM-DD'), start.add(6, 'day').format('YYYY-MM-DD')];
};

const nextWeek = () => {
    const start = dayjs(dateRange.value[0]).add(7, 'day');
    dateRange.value = [start.format('YYYY-MM-DD'), start.add(6, 'day').format('YYYY-MM-DD')];
};

const currentWeek = () => {
    const [start, end] = getDefaultDateRange();
    dateRange.value = [start, end];
};
</script>
<template>
    <el-row>
        <el-col :span="24">
            <div class="grid-content ep-bg-purple-dark shadow-box">
                <el-row>
                    <el-col :span="12"></el-col>
                    <el-col :span="12">
                        <el-button type="primary" :icon='Plus' @click="prevWeek">上一周</el-button>
                        <el-button type="success" :icon="'Finished'" @click="currentWeek">当前周</el-button>
                        <el-button type="primary" :icon='"Check"' @click="nextWeek">下一周</el-button>
                    </el-col>
                </el-row>
            </div>
        </el-col>
        <el-col :span="24">
            <div class="grid-content ep-bg-purple-dark shadow-box">
                <el-row>
                    <el-col :span="24"><span>{{ dateRange[0] }}(周一)</span> <span>{{ dateRange[1] }}(周末)</span></el-col>

                </el-row>
            </div>
        </el-col>
        <el-col :span="24">
            <div >
                <el-row>
                    <el-col :span="24">
                        <el-table :data="Pages" border :header-cell-style="headerCellStyle">
  <el-table-column prop="userName" label="医生" width="100" align="center" />
  <el-table-column prop="deptName" label="科室" width="100" align="center" />
  <el-table-column label="时段/日期" width="100" align="center">
                <template #default="scope">
                    <div class="time-slots">
                        <div>上午</div>
                        <div>下午</div>
                        <div>晚上</div>
                    </div>
                </template>
            </el-table-column>
  <!-- 日期列 -->
  <el-table-column 
    v-for="(day, index) in weekDays" 
    :key="index" 
    :label="formatDay(day.date)"
    align="center">
    <template #default="{ row }">
      <div class="schedule-slots">
        <!-- 上午 -->
        <div class="slot-item" 
             :class="{ 'has-schedule': hasMorningSchedule(row, day.date) }">
          {{ getMorningSchedule(row, day.date) }}
        </div>
        <!-- 中午 -->
        <div class="slot-item" 
             :class="{ 'has-schedule': hasAfternoonSchedule(row, day.date) }">
          {{ getAfternoonSchedule(row, day.date) }}
        </div>
        <!-- 晚上 -->
        <div class="slot-item" 
             :class="{ 'has-schedule': hasEveningSchedule(row, day.date) }">
          {{ getEveningSchedule(row, day.date) }}
        </div>
      </div>
    </template>
  </el-table-column>
</el-table>
                    </el-col>
                </el-row>
            </div>
        </el-col>
    </el-row>

</template>
<style scoped>
/* 布局样式 */
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

/* 背景阴影 */
.shadow-box {
    width: 96%;
    height: 100px;
    background-color: #fff;
    /* 水平偏移量 垂直偏移量 模糊半径 扩散半径 颜色 */
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    text-align: center;
    line-height: 100px;
    border-radius: 8px;
    margin: 20px;
}
.schedule-container {
    padding: 20px;
}

.search-area {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 10px;
}

.search-item {
    display: flex;
    align-items: center;
}

.label {
    margin-right: 8px;
    white-space: nowrap;
}

.date-picker-area {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 20px;
}

.date-display {
    font-size: 16px;
    color: #606266;
    font-weight: bold;
}

.time-slots {
    display: flex;
    flex-direction: column;
    height: 120px;
}

.time-slots div {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #ebeef5;
}

.time-slots div:last-child {
    border-bottom: none;
}

.schedule-slots {
    display: flex;
    flex-direction: column;
    height: 120px;
}

.slot-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #ebeef5;
    color: #909399;
}

.slot-item:last-child {
    border-bottom: none;
}

.has-schedule {
    color: #409EFF;
    font-weight: bold;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>